const postcss = require('postcss');
var autoprefixer = require('autoprefixer');
var postcssNested = require('postcss-nested');
var tailwindcss = require('tailwindcss');
var sass = require('sass');
var cssnano = require('cssnano');
const fs = require('fs');

const { writeFile } = require('../../../app/util');

function compilerStyle(option, theme, isWrite = true, callback, callError) {
  console.log('------css编译模版' + theme);

  fs.readFile(option.from, (err, css) => {
    if (err) {
      console.error(err);
    }
    try {
      // const body = css.replace(/\@\//g, `./src/theme/${theme}/lib/style/`);
      const sassResult = sass.compile(option.from);
      postcss([
        tailwindcss({
          purge:option.purge || [`./src/theme/${theme}/**/*.liquid`],
          prefix: theme === 'default' ? 'df-' : '',
          content: [],
          theme: {
            extend: {},
          },
          plugins: [],
          corePlugins: {
            preflight: false,
          },
        }),
        autoprefixer,
        postcssNested,
        cssnano({
          preset: 'default',
        }),
      ])
        .process(`@import "tailwindcss/components"; @import "tailwindcss/utilities";` + sassResult.css, option)
        .then((result) => {
          isWrite && writeFile(option.to, result.css);
          callback && callback(result.css);
        });
    } catch (error) {
      console.log('css编译出错', error);
      callError && callError();
    }
  });
}

function compilerPostcss(option, theme) {
  postcss([autoprefixer, postcssNested])
    .process(css, option)
    .then((result) => {
      const body = result.css.replace(/\@\//g, `./src/theme/${theme}/lib/style/`);
      var content = sass.renderSync({ file: body }).css;
      console.log(option.to);
      isWrite && writeFile(option.to, content);
      callback && callback(content);
    });
}

module.exports = { compilerStyle };
